﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ProductServiceReference;
using CategoryServiceReference;
using System.ServiceModel;

public partial class UserControls_FindProduct : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(IsPostBack) return;
        var client = new CategoryServiceClient();
        foreach (var item in client.GetCategories())
        {
            ddlCategory.Items.Add(new ListItem(item.CategoryName, item.CategoryID + ""));
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            LoadData();
            UpdatePanel1.Update();
        }
        catch (FaultException<Product> faultException)
        {
            lblmsg.Text = "Khong co san pham nao";
        }
        catch (FaultException<Category> faultException)
        {
            lblmsg.Text = "Khong co san pham nao";
        }
        catch (Exception ex)
        {
            lblmsg.Text = ex.Message;
        }
    }
    protected void GridView1_PageIndexChanged(object sender, EventArgs e)
    {
        LoadData();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
    }

    private void LoadData()
    {
        var client = new ProductServiceClient();
        var keySearch = txtKeySearch.Text.Trim();
        var catid = int.Parse(ddlCategory.SelectedValue);
        var result = client.FindProduct(keySearch, catid);
        if (result == null)
        {
            lblmsg.Text = "Khong co ket qua";
        }
        else
        {
            GridView1.DataSource = result;
            GridView1.DataBind();
        }
    }
}